package com.kgc.rb.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;

import com.alipay.api.internal.util.AlipaySignature;
import com.kgc.rb.common.tools.Constants;
import com.kgc.rb.common.tools.IdWorker;
import com.kgc.rb.configuration.AlipayConfig;
import com.kgc.rb.pojo.QgGoods;
import com.kgc.rb.pojo.QgGoodsTempStock;
import com.kgc.rb.pojo.QgOrder;
import com.kgc.rb.pojo.QgTrade;
import com.kgc.rb.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.monitor.StringMonitor;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class LocalTradeServiceImpl implements LocalTradeService {
    @Reference(check = false)
    private QgOrderService qgOrderService;
    @Reference(check = false)
    private QgGoodsService qgGoodsService;
    @Reference(check = false)
    private QgGoodsTempStockService qgGoodsTempStockService;
    @Reference(check = false)
    private QgTradeService qgTradeService;
    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public boolean validateAliPay(HttpServletRequest request, String methodType) throws Exception {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = getParamsMap(request, methodType);
        //验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.alipay_public_key, alipayConfig.charset, alipayConfig.sign_type); //调用SDK验证签名
        return signVerified;
    }

    public Map<String, String> getParamsMap(HttpServletRequest request, String methodType) throws UnsupportedEncodingException {
        //获取支付宝GET过来反馈信息
        if (methodType.equals("POST")) {
            request.setCharacterEncoding("UTF-8");
        }
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            if (methodType.equals("GET")) {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            }
            params.put(name, valueStr);
        }
        return params;
    }

    @Override
    public QgOrder getOrderById(String orderId) throws Exception {
        QgOrder qgOrder = qgOrderService.getQgOrderById(orderId);
        return qgOrder;
    }

    @Override
    public QgGoods getGoodsByGoodsId(String goodsId) throws Exception {
        QgGoods qgGoods = qgGoodsService.getQgGoodsById(goodsId);
        return qgGoods;
    }

    //支付成功之后更新数据库的操作
    @Override
    public String dealPayStatus(String out_trade_no, String trade_no) throws Exception {
        //根据订单编号查询订单信息

        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", out_trade_no);
        List<QgOrder> qgOrderList = qgOrderService.getQgOrderListByMap(params);
        QgOrder order = qgOrderList.get(0);
        //1.修改订单的状态
        updateOrder(order);
        //2.修改临时库存表中的状态
        updateGoodsTempStock(order);
        //3.向交易表中添加交易记录
        saveTrade(order, trade_no);
        return order.getId();
    }

    @Override
    public boolean validateDealPayStatus(String trade_no) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("tradeNo", trade_no);
        Integer qgTradeCountByMap = qgTradeService.getQgTradeCountByMap(params);
        if (qgTradeCountByMap > 0) {//说明数据库中已经有这条数据
            return true;
        }
        return false;
    }

    private void saveTrade(QgOrder order, String trade_no) throws Exception {
        QgTrade trade = new QgTrade();
        trade.setId(IdWorker.getId());
        trade.setOrderNo(order.getOrderNo());
        trade.setPayMethod(Constants.PayMethod.ALIPAY);
        trade.setTradeNo(trade_no);
        trade.setAmount(order.getAmount());
        trade.setCreatedTime(new Date());
        trade.setUpdatedTime(new Date());
        qgTradeService.qdtxAddQgTrade(trade);
    }

    private void updateGoodsTempStock(QgOrder order) throws Exception {
        QgGoodsTempStock qgGoodsTempStock = qgGoodsTempStockService.getQgGoodsTempStockById(order.getStockId());
        qgGoodsTempStock.setStatus(Constants.GoodsStatus.PAID);
        qgGoodsTempStock.setUpdatedTime(new Date());
        qgGoodsTempStockService.qdtxModifyQgGoodsTempStock(qgGoodsTempStock);
    }

    private void updateOrder(QgOrder order) throws Exception {
        order.setStatus(Constants.PayStatus.PAYSUCCESS);
        order.setUpdatedTime(new Date());
        qgOrderService.qdtxModifyQgOrder(order);
    }
}
